<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='800px'
          :title="isAdd?'新增':title"
          @ok="submit"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 100%;">
              <a-form-model  layout="inline">
                <a-form-model-item
                    class='optionTitle'
                    label="保养项目编码"
                    style="margin-left: 0"
                    required
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.code'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="保养项目名称"
                    style="margin-left: 0"
                    required
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.name'  v-auth="`query`"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="单位"
                    prop="unit"
                    style="margin-left: 67px">
                  <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '200px' }">
                    <template slot="content">
                      <p class="aPopover" v-for="(item,index) in unitSearchList" :key="index"  @click="changeUnit(item)" >{{item.name}}</p>
                    </template>
                    <a-input style='width: 200px;height: 32px;'
                             v-model.trim="addForm.unit_name"
                             @keydown.enter="getUnitIdByNameLimit(addForm.unit_name)"
                             @change="getUnitIdByNameLimit(addForm.unit_name)"
                             :disabled="!canBeEdited || !isAdd"
                             allowClear
                             @click="getUnitIdByNameLimit(addForm.unit_name)"
                             placeholder="输入搜索并从列表选择"></a-input>
                  </a-popover>
                </a-form-model-item>

                <a-form-model-item
                    class='optionTitle'
                    label="标准值"
                    style="margin-left: 53px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.standard_value'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="上限"
                    style="margin-left: 67px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.upper_limit'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="下限"
                    style="margin-left: 67px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.lower_limit'  v-auth="`query`"></a-input>
                </a-form-model-item>
              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <!--详情-->
      <a-modal
          destroyOnClose
          v-model='detailModal'
          width='800px'
          :title="isAdd?'详情':title"
          @ok="submitDetail"
          @cancel="handleCancelDetail"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 100%;">
              <a-form-model  layout="inline">
                <a-form-model-item
                    class='optionTitle'
                    label="保养项目编码"
                    style="margin-left: 0"
                    required
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.code'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="保养项目名称"
                    style="margin-left: 0"
                    required
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.name'  v-auth="`query`"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="单位"
                    prop="unit"
                    style="margin-left: 67px">
                  <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '200px' }">
                    <template slot="content">
                      <p class="aPopover" v-for="(item,index) in unitSearchList" :key="index"  @click="changeUnit(item)" >{{item.name}}</p>
                    </template>
                    <a-input style='width: 200px;height: 32px;'
                             v-model.trim="addForm.unit_name"
                             @keydown.enter="getUnitIdByNameLimit(addForm.unit_name)"
                             @change="getUnitIdByNameLimit(addForm.unit_name)"
                             :disabled="!canBeEdited || !isAdd"
                             allowClear
                             @click="getUnitIdByNameLimit(addForm.unit_name)"
                             placeholder="输入搜索并从列表选择"></a-input>
                  </a-popover>
                </a-form-model-item>

                <a-form-model-item
                    class='optionTitle'
                    label="标准值"
                    style="margin-left: 53px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.standard_value'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="上限"
                    style="margin-left: 67px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.upper_limit'  v-auth="`query`"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    class='optionTitle'
                    label="下限"
                    style="margin-left: 67px"
                >
                  <a-input style='width: 200px;height: 32px' v-model.trim='addForm.lower_limit'  v-auth="`query`"></a-input>
                </a-form-model-item>

              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 90px;display: flex;justify-content: space-around">
<!--          <a-badge count="9">-->
            <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
<!--          </a-badge>-->
        </div>
      </page-head-area>

      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordMain) => {return recordMain.id}"
            :scroll="{ x: 1000, y: 500 }"
        >
          <template slot="action" slot-scope="record">
            <a v-auth="`query`" @click="openDetail(record)">详情</a>
          </template>
        </a-table>

      </div>
      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>

    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";
import moment from "moment";
import {
  file_import, file_upload,
  get_employee_list,
  get_extended_define, get_asset_file_list, get_supplier, get_unit_list, download_file,
  get_organization_list,
  delete_asset, get_asset_list, save_asset, update_asset,
  get_category_type_list, get_organization_profile_list, get_template_list, update_extend
} from "@/services/manage";
import {
  deleteDeviceInspectionPlan,
  deleteDeviceRepair, getCacheById,
  getCacheByVaguename,
  getDeviceList, getUnitIdByName,
  getUserNameById,
  listDeviceGrade,
  listDeviceInspectionPlan,
  listDeviceMaintenanceProject,
  listDeviceMaintenanceType,
  listDeviceType,
  listSpareParts,
  saveDeviceInspectionPlan, saveDeviceMaintenanceProject, saveDeviceMaintenanceType
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {list_device_maintenance_project} from "../../services/basicInformation";
const data = []

const addData =[]

const columns = [
  { title: '保养项目序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '保养项目编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '保养项目名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '单位', width: 120, align:'center',dataIndex: 'unit_name', key: 'unit_name'},
  { title: '标准值', width: 120, align:'center',dataIndex: 'standard_value', key: 'standard_value'},
  { title: '上限', width: 120, align:'center',dataIndex: 'upper_limit', key: 'upper_limit'},
  { title: '下限', width: 120, align:'center',dataIndex: 'lower_limit', key: 'lower_limit'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const addColumns = [

  { title: '序号', width: 120, align:'center',dataIndex: 'device_id', key: 'device_id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '规格', width: 120, align:'center',dataIndex: 'specification', key: 'specification'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      unitSearchList:[],
      record:{},
      addForm:{
        code:undefined,
        name:undefined,
        standard_value:undefined,
        upper_limit:undefined,
        lower_limit:undefined,
        unit_id:undefined,
        unit_name:undefined,
      },
      addColumns,
      addData,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        plan_status:undefined,
        dateSelect:[],
      },
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      maintenance_detailsModal:false,
      addPagination:{
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      }
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    this.axiosSource = axios.CancelToken.source();

    await this.initialize()

  },
  methods: {
    changeUnit(item){
      console.log(item)
      this.addForm.unit_id=item.id
      this.addForm.unit_name=item.name
      this.unitSearchList=[]
    },
    openDetail(record){
      this.clearParams()
      this.addForm.code=record.code
      this.addForm.name=record.name
      this.addForm.unit_id=record.unit_id
      this.addForm.unit_name=record.unit_name
      this.addForm.standard_value=record.standard_value
      this.addForm.upper_limit=record.upper_limit
      this.addForm.lower_limit=record.lower_limit
      this.detailModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      this.record=record
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    async initialize(){
      this.tableLoading =true
      this.data=[]
      const paramsAll = Object.assign({}, {}, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });

      await list_device_maintenance_project(paramsAll).then(async res => {
        if(res.data.code==='1000'){
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const listItem of res.data.data) {
            let searchItem = await getCacheById(listItem.unit_id)
            listItem['unit_name'] = searchItem.name
          }
          this.data=res.data.data
        }


        console.log(this.data)
        this.tableLoading =false

      })
      this.tableLoading =false
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    onChangeAdd(pagination){
      this.addPagination.current = pagination.current
      this.addPagination.page_size = pagination.pageSize
      this.addPagination.page = pagination.current
    },
    async query() {
      this.tableLoading = true
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      this.tableLoading = false
      await this.initialize()

    },
    reset() {
      this.query()
    },
    add() {
      this.clearParams()
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      //清空
    },
    clearParams(){
      this.addForm={
        code:undefined,
        name:undefined,
        standard_value:undefined,
        upper_limit:undefined,
        lower_limit:undefined,
        unit_id: undefined,
        unit_name: undefined,
      }
    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    detail(record) {
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    handleCancel0() {
      this.addModal = false
      this.clearParams()
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancelDetail(){
      this.detailModal = false
      this.clearParams()
      this.canBeEdited = false
      this.isAdd = false
    },
    async submit() {
      //检查有无
      if(this.addForm.code===undefined || this.addForm.name===undefined || this.addForm.code==='' || this.addForm.name===''){
        message.error('请填写必填项')

      }
      else {
        //code查重
        let searchList = await listDeviceMaintenanceProject({'code':this.addForm.code})
        let flag=true
        for (let i = 0; i < searchList.length; i++) {
          if(searchList[i].code===this.addForm.code) {
            flag = false
            break;
          }
        }
        if(flag===false){
          message.error('保养项目编码已存在')
        }
        else{
          // // await
          await saveDeviceMaintenanceProject({
            'code': this.addForm.code,
            'name': this.addForm.name,
            'unit_id':this.addForm.unit_id,
            'standard_value':this.addForm.standard_value,
            'upper_limit':this.addForm.upper_limit,
            'lower_limit':this.addForm.lower_limit,

          })
          this.clearParams()
          message.success('添加成功')
          this.addModal = false
          //重新加载
          await this.initialize()
        }
      }


    },
    async getUnitIdByNameLimit(unit_name) {
      await getUnitIdByName(unit_name).then(res => {
        //添加res中值到supplierSearchList
        this.unitSearchList = []
        res.slice(0, 10).forEach(item => {
          this.unitSearchList.push({
            id: item.id,
            name: item.name
          })
        })
      })
    },
    async submitDetail() {
      //检查有无
      if (this.addForm.code === undefined || this.addForm.name === undefined || this.addForm.code === '' || this.addForm.name === '') {
        message.error('请填写必填项')

      } else {
        //code查重
        let searchList
        let flag = true
        if (this.record.code !== this.addForm.code) {
          searchList = await listDeviceMaintenanceProject({'code': this.addForm.code})
          console.log(searchList)
          for (let i = 0; i < searchList.length; i++) {
            if (searchList[i].code === this.addForm.code) {
              flag = false
              break;
            }
          }
        }

        if (flag === false) {
          message.error('保养项目编码已存在')
        } else {
          await saveDeviceMaintenanceProject({
            'id': this.record.id,
            'code': this.addForm.code,
            'name': this.addForm.name,
            'unit_id':this.addForm.unit_id,
            'standard_value':this.addForm.standard_value,
            'upper_limit':this.addForm.upper_limit,
            'lower_limit':this.addForm.lower_limit
          })
          this.clearParams()
          message.success('修改成功')
          this.detailModal = false
          //重新加载
          await this.initialize()
        }


      }
    },
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">
.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}


.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>